package com.lixixi.tingshu.album.service.impl;

import com.lixixi.tingshu.album.properties.MinioProperties;
import com.lixixi.tingshu.album.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
	@Resource
	MinioClient minioClient;

	@Resource
	MinioProperties minioProperties;

	@Override
	public String fileUpload(InputStream inputStream, String oldFileName, Long size, String fileContentType) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
		//使用uuid随机生成图片名字
		String newFileName = UUID.randomUUID().toString().replace("-","") + "." + FilenameUtils.getExtension(oldFileName);
		//获取桶名
		String bucketName = minioProperties.getBucketName();
		//判断桶是否存在
		boolean found =
				minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
		if (!found)
		{
			// Make a new bucket.
			minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
		} else
		{
			System.out.println("Bucket: " + bucketName + " already exists.");
		}
		// Upload known sized input stream.
		minioClient.putObject(
				PutObjectArgs.builder().bucket(minioProperties.getBucketName()).object(newFileName).stream(
								inputStream, size, -1)
						.contentType(fileContentType)
						.build());
		//返回文件路径
		return minioProperties.getEndPoint() + "/" + minioProperties.getBucketName() + "/" + newFileName;
	}
}
